<template>
  <div class="personal-center-wrapper">
    <!-- 导航栏 -->
    <HomeNavBar />
    
    <div class="personal-center">
    <!-- 个人信息卡片 -->
    <el-card class="user-info-card">
      <div class="user-header">
        <el-avatar :size="80" :src="userInfo.avatar || undefined">
          {{ userInfo.username?.charAt(0)?.toUpperCase() }}
        </el-avatar>
        <div class="user-details">
          <h2>{{ userInfo.username || '未登录' }}</h2>
          <p class="user-role">{{ getRoleText(userInfo.role) }}</p>
        </div>
      </div>
    </el-card>

    <!-- Tab 切换 -->
    <el-card class="tabs-card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 投递记录 Tab -->
        <el-tab-pane label="投递记录" name="applications">
          <template #label>
            <span class="custom-tab-label">
              <el-icon><Document /></el-icon>
              投递记录
            </span>
          </template>

      <div class="tab-content">
        <div class="card-header">
          <h3>
            <el-icon><List /></el-icon>
            我的投递记录
          </h3>
          <div class="header-actions">
            <el-select v-model="statusFilter" placeholder="筛选状态" style="width: 150px" @change="fetchApplications">
              <el-option label="全部" value="all" />
              <el-option label="待处理" value="pending" />
              <el-option label="面试中" value="interviewing" />
              <el-option label="已通过" value="accepted" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
            <el-button :icon="Refresh" @click="fetchApplications">刷新</el-button>
          </div>
        </div>

      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" :size="40"><Loading /></el-icon>
        <p>加载中...</p>
      </div>

      <div v-else-if="applications.length === 0" class="empty-state">
        <el-empty description="暂无投递记录">
          <el-button type="primary" @click="$router.push('/jobs')">
            去投递岗位
          </el-button>
        </el-empty>
      </div>

      <div v-else class="applications-list">
        <div v-for="app in applications" :key="app.applicationId" class="application-item">
          <div class="app-header">
            <div class="job-info">
              <h4>{{ app.job?.jobName || '未知岗位' }}</h4>
              <p class="company-name">
                <el-icon><OfficeBuilding /></el-icon>
                {{ app.job?.enterprise?.enterpriseName || '未知公司' }}
              </p>
            </div>
            <el-tag :type="getStatusType(app.status)" size="large">
              {{ getStatusText(app.status) }}
            </el-tag>
          </div>
          
          <div class="app-details">
            <div class="detail-item">
              <span class="label">投递简历：</span>
              <span class="value">{{ app.resumeName || '未知简历' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">投递时间：</span>
              <span class="value">{{ formatTime(app.applyTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">岗位地点：</span>
              <span class="value">{{ app.job?.location || '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">薪资范围：</span>
              <span class="value">{{ app.job?.salary || '-' }}</span>
            </div>
          </div>

          <div class="app-actions">
            <el-button size="small" @click="viewJobDetail(app.job)">查看岗位</el-button>
            <el-button size="small" @click="viewApplicationDetail(app)">查看详情</el-button>
            <el-button 
              v-if="app.status === 'pending'" 
              size="small" 
              type="danger"
              @click="handleWithdraw(app)"
            >
              撤回投递
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="applications.length > 0" class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="totalApplications"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      </div>
        </el-tab-pane>

        <!-- 收藏岗位 Tab -->
        <el-tab-pane label="收藏岗位" name="favorites">
          <template #label>
            <span class="custom-tab-label">
              <el-icon><Star /></el-icon>
              收藏岗位
            </span>
          </template>

          <div class="tab-content">
            <div class="card-header">
              <h3>
                <el-icon><Star /></el-icon>
                我的收藏岗位
              </h3>
              <div class="header-actions">
                <el-button :icon="Refresh" @click="fetchFavoriteJobs">刷新</el-button>
              </div>
            </div>

            <div v-if="loadingFavorites" class="loading-container">
              <el-icon class="is-loading" :size="40"><Loading /></el-icon>
              <p>加载中...</p>
            </div>

            <div v-else-if="favoriteJobs.length === 0" class="empty-state">
              <el-empty description="暂无收藏岗位">
                <el-button type="primary" @click="$router.push('/jobs')">
                  去浏览岗位
                </el-button>
              </el-empty>
            </div>

            <div v-else class="favorites-list">
              <div v-for="fav in favoriteJobs" :key="fav.id" class="favorite-item">
                <div class="fav-header">
                  <div class="job-info">
                    <h4>{{ fav.favoriteJob?.jobName || '未知岗位' }}</h4>
                    <p class="company-name">
                      <el-icon><OfficeBuilding /></el-icon>
                      {{ fav.favoriteJob?.enterprise?.enterpriseName || '未知公司' }}
                    </p>
                  </div>
                  <el-tag type="success" size="large">
                    <el-icon><Star /></el-icon>
                    已收藏
                  </el-tag>
                </div>

                <div class="fav-details">
                  <div class="detail-item">
                    <span class="label">工作地点：</span>
                    <span class="value">{{ fav.favoriteJob?.location || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">薪资范围：</span>
                    <span class="value">{{ fav.favoriteJob?.salary || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">工作经验：</span>
                    <span class="value">{{ fav.favoriteJob?.experience || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">收藏时间：</span>
                    <span class="value">{{ formatTime(fav.created_at) }}</span>
                  </div>
                </div>

                <div class="fav-actions">
                  <el-button size="small" @click="viewJobDetail(fav.favoriteJob)">查看详情</el-button>
                  <el-button size="small" type="danger" @click="handleUncollect(fav)">
                    <el-icon><Delete /></el-icon>
                    取消收藏
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div v-if="favoriteJobs.length > 0" class="pagination-section">
              <el-pagination
                v-model:current-page="favCurrentPage"
                v-model:page-size="favPageSize"
                :page-sizes="[10, 20, 50]"
                :total="totalFavorites"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleFavSizeChange"
                @current-change="handleFavCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 岗位详情对话框 -->
    <el-dialog
      v-model="jobDetailVisible"
      :title="currentJob?.jobName"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentJob" class="job-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="公司名称">
            {{ currentJob.enterprise?.enterpriseName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="岗位状态">
            <el-tag :type="currentJob.jobStatus === 'active' ? 'success' : 'info'">
              {{ currentJob.jobStatus === 'active' ? '招聘中' : '已暂停' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工作地点">
            {{ currentJob.location }}
          </el-descriptions-item>
          <el-descriptions-item label="薪资范围">
            {{ currentJob.salary }}
          </el-descriptions-item>
          <el-descriptions-item label="工作经验">
            {{ currentJob.experience }}
          </el-descriptions-item>
          <el-descriptions-item label="学历要求">
            {{ currentJob.education }}
          </el-descriptions-item>
          <el-descriptions-item label="岗位分类">
            {{ currentJob.category }}
          </el-descriptions-item>
          <el-descriptions-item label="招聘人数">
            {{ currentJob.hiringCount }}人
          </el-descriptions-item>
        </el-descriptions>

        <div class="job-section">
          <h3>岗位描述</h3>
          <p>{{ currentJob.jobDescription }}</p>
        </div>

        <div class="job-section">
          <h3>任职要求</h3>
          <p>{{ currentJob.jobRequirements }}</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="jobDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 投递详情对话框 -->
    <el-dialog
      v-model="appDetailVisible"
      title="投递详情"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentApplication" class="application-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="岗位名称">
            {{ currentApplication.job?.jobName }}
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">
            {{ currentApplication.job?.enterprise?.enterpriseName }}
          </el-descriptions-item>
          <el-descriptions-item label="投递简历">
            {{ currentApplication.resumeName }}
          </el-descriptions-item>
          <el-descriptions-item label="投递时间">
            {{ formatTime(currentApplication.applyTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getStatusType(currentApplication.status)">
              {{ getStatusText(currentApplication.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="currentApplication.resumeUrl" class="resume-download">
          <h4>简历文件</h4>
          <el-button type="primary" @click="downloadResume(currentApplication.resumeUrl)">
            <el-icon><Download /></el-icon>
            下载简历
          </el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="appDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 撤回确认对话框 -->
    <el-dialog
      v-model="withdrawDialogVisible"
      title="撤回投递"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="confirm-content">
        <div class="confirm-icon">
          <el-icon :size="48" color="#e6a23c"><Warning /></el-icon>
        </div>
        <div class="confirm-message">
          确定要撤回对"{{ currentWithdrawApp?.job?.jobName }}"的投递申请吗？
        </div>
      </div>

      <template #footer>
        <el-button @click="withdrawDialogVisible = false">取消</el-button>
        <el-button type="danger" :loading="withdrawing" @click="confirmWithdraw">
          确定撤回
        </el-button>
      </template>
    </el-dialog>
  </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Document, 
  Clock, 
  VideoCamera, 
  SuccessFilled, 
  List, 
  Refresh, 
  Loading,
  OfficeBuilding,
  Warning,
  Download,
  Star,
  Delete
} from '@element-plus/icons-vue'
import { getUserApplications, withdrawApplication, getUserFavoriteJobs, uncollectJob } from '@/api/enterprise'
import useStore from '@/store'
import HomeNavBar from '@/components/HomeNavBar.vue'

const store = useStore()

// 用户信息
const userInfo = computed(() => store.app)

// Tab 切换
const activeTab = ref('applications')

// 投递记录数据
const applications = ref([])
const allApplications = ref([]) // 用于统计的全部数据
const loading = ref(false)
const statusFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const totalApplications = ref(0)

// 收藏岗位数据
const favoriteJobs = ref([])
const loadingFavorites = ref(false)
const favCurrentPage = ref(1)
const favPageSize = ref(10)
const totalFavorites = ref(0)

// 对话框状态
const jobDetailVisible = ref(false)
const appDetailVisible = ref(false)
const withdrawDialogVisible = ref(false)
const currentJob = ref(null)
const currentApplication = ref(null)
const currentWithdrawApp = ref(null)
const withdrawing = ref(false)

// 投递统计
const statistics = computed(() => {
  const stats = {
    total: totalApplications.value,
    pending: 0,
    interviewing: 0,
    accepted: 0,
    rejected: 0
  }

  allApplications.value.forEach(app => {
    if (app.status === 'pending') stats.pending++
    else if (app.status === 'interviewing') stats.interviewing++
    else if (app.status === 'accepted') stats.accepted++
    else if (app.status === 'rejected') stats.rejected++
  })

  return stats
})

// 获取用户角色文本
const getRoleText = (role) => {
  const roleMap = {
    user: '求职者',
    enterprise: '企业用户',
    admin: '管理员'
  }
  return roleMap[role] || '未知角色'
}

// 获取所有投递记录用于统计
const fetchAllApplicationsForStats = async () => {
  try {
    const response = await getUserApplications({ page: 1, pageSize: 1000 })
    allApplications.value = response?.data?.list || response?.list || []
    console.log(`📊 获取到 ${allApplications.value.length} 条投递记录用于统计`)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    allApplications.value = []
  }
}

// 获取投递记录
const fetchApplications = async () => {
  loading.value = true
  try {
    const params = {
      status: statusFilter.value !== 'all' ? statusFilter.value : undefined,
      page: currentPage.value,
      pageSize: pageSize.value
    }

    console.log('📝 获取用户投递记录', params)

    const response = await getUserApplications(params)
    applications.value = response?.data?.list || response?.list || []
    totalApplications.value = response?.data?.total || response?.total || 0

    console.log(`✅ 获取到 ${applications.value.length} 条投递记录，总计 ${totalApplications.value} 条`)
  } catch (error) {
    console.error('获取投递记录失败:', error)
    ElMessage.error('获取投递记录失败，请重试')
    applications.value = []
    totalApplications.value = 0
  } finally {
    loading.value = false
  }
}

// 查看岗位详情
const viewJobDetail = (job) => {
  currentJob.value = job
  jobDetailVisible.value = true
}

// 查看投递详情
const viewApplicationDetail = (app) => {
  currentApplication.value = app
  appDetailVisible.value = true
}

// 处理撤回
const handleWithdraw = (app) => {
  currentWithdrawApp.value = app
  withdrawDialogVisible.value = true
}

// 确认撤回
const confirmWithdraw = async () => {
  if (!currentWithdrawApp.value) return

  withdrawing.value = true
  try {
    await withdrawApplication(currentWithdrawApp.value.applicationId)
    ElMessage.success('投递已撤回')
    withdrawDialogVisible.value = false
    
    // 刷新列表和统计数据
    await Promise.all([
      fetchApplications(),
      fetchAllApplicationsForStats()
    ])
  } catch (error) {
    console.error('撤回失败:', error)
    ElMessage.error(error.message || '撤回失败，请重试')
  } finally {
    withdrawing.value = false
  }
}

// 下载简历
const downloadResume = (url) => {
  window.open(url, '_blank')
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchApplications()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchApplications()
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '-'
  const date = new Date(timeString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    interviewing: 'primary',
    accepted: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待处理',
    interviewing: '面试中',
    accepted: '已通过',
    rejected: '已拒绝'
  }
  return textMap[status] || '未知'
}

// Tab 切换处理
const handleTabChange = (tabName) => {
  if (tabName === 'favorites') {
    fetchFavoriteJobs()
  }
}

// 获取收藏岗位列表
const fetchFavoriteJobs = async () => {
  loadingFavorites.value = true
  try {
    const params = {
      page: favCurrentPage.value,
      pageSize: favPageSize.value
    }

    console.log('📝 获取用户收藏岗位', params)

    const response = await getUserFavoriteJobs(params)
    favoriteJobs.value = response?.data?.list || response?.list || []
    totalFavorites.value = response?.data?.total || response?.total || 0

    console.log(`✅ 获取到 ${favoriteJobs.value.length} 个收藏岗位，总计 ${totalFavorites.value} 个`)
  } catch (error) {
    console.error('获取收藏岗位失败:', error)
    ElMessage.error('获取收藏岗位失败，请重试')
    favoriteJobs.value = []
    totalFavorites.value = 0
  } finally {
    loadingFavorites.value = false
  }
}

// 取消收藏
const handleUncollect = async (favorite) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消收藏"${favorite.favoriteJob?.jobName}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const jobId = favorite.job_id
    await uncollectJob(jobId)
    ElMessage.success('已取消收藏')

    // 刷新收藏列表
    await fetchFavoriteJobs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error)
      ElMessage.error('取消收藏失败，请重试')
    }
  }
}

// 收藏岗位分页处理
const handleFavSizeChange = (val) => {
  favPageSize.value = val
  favCurrentPage.value = 1
  fetchFavoriteJobs()
}

const handleFavCurrentChange = (val) => {
  favCurrentPage.value = val
  fetchFavoriteJobs()
}

// 页面加载时获取数据
onMounted(() => {
  Promise.all([
    fetchApplications(),
    fetchAllApplicationsForStats()
  ])
})
</script>

<style scoped src="@/assets/style/user/personal-center.css"></style>
